package com.it.park.controller.admin;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.client.service.ArticleService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.common.SessionUtil;
import com.it.park.constant.Constant;
import com.it.park.model.Article;

@Controller
@RequestMapping("/admin/article")
public class AdminArticleController {
	
	private String rootPath=Constant.ADMIN_PATH;

	private Page page = null;
	@Autowired
	private ArticleService articleService;
	@RequestMapping("listRows")
	@ResponseBody
	public Map<String,Object> listRows(HttpServletRequest request){

		int pageNow = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		Map<String,Object> map_ = new HashMap<String, Object>();
		Integer total = articleService.selectTotal(map_);
		if(page != null){
			page = new Page(pageNow,total,rows);
		}else{
			page = new Page(1,total,rows);
		}
		map_.put("startPos", page.getStartPos());
		map_.put("pageSize", page.getPageSize());
		List<Article> list = articleService.selectPagination(map_);
		Map<String,Object> map  =new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", list);
		return map;
	}
	
	@RequestMapping("articleList")
	public String articleList(HttpServletRequest request){
			return rootPath+"article/articleList";
	}
	
	/**
	 *单个文章详情 
	 */
	@RequestMapping("detail")
	public String detail(HttpServletRequest request){
		return "jsp/article/articleDetail";
	}
	
	
	@RequestMapping("save")
	@ResponseBody
	public JsonObj save(Article article,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = articleService.insertSelective(article);
		if(success){
			json.setMessage("添加成功!");
		}else{
			json.setMessage("添加失败!");
		}
		json.setSuccess(success);
		return json;
	}
	
	@RequestMapping("deleteById")
	@ResponseBody
	public JsonObj deleteById(@RequestParam("id") int id,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = articleService.deleteByPrimaryKey(id);
		if(success){
			json.setMessage("删除成功!");
		}else{
			json.setMessage("删除失败!");
		}
		json.setSuccess(success);
		return json;
	}
	
	@RequestMapping("edit")
	@ResponseBody
	public JsonObj edit(Article article,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = articleService.updateByPrimaryKeySelective(article);
		if(success){
			json.setMessage("修改成功!");
		}else{
			json.setMessage("修改失败!");
		}
		json.setSuccess(success);
		return json;
	}
	
	
	/**
	 * 抓取文章
	 * */
	@RequestMapping("grab")
	@ResponseBody
	public JsonObj grab(HttpServletRequest request,HttpSession session){
		JsonObj json = new JsonObj();
		try {
			
			String url = "http://blog.csdn.net/cyh1111/article/category/536110";
			Document document;
				document = Jsoup.connect(url)
						.timeout(5000)
						.get();
				Elements es = document.select(".link_title>a");
				for (int i = 0; i < es.size(); i++) {
					Element e = es.get(i);
					String href = e.attr("href");
					String text = e.text();
					Document doc= Jsoup.connect("http://blog.csdn.net"+href)
							.timeout(5000)
							.get();
//					System.out.println(doc.select(".description"));
					Element ess = doc.select("#article_content").first();
					if(ess != null){
						String articleContent = ess.toString();
						if(articleContent != null && !"".equals(articleContent) && !"null".equals(articleContent)){
							Article article = new Article();
							article.setArticleTitle(text);
							article.setArticleBriefIntroduction(text);
							article.setArticleContent(articleContent);
							article.setUserId(SessionUtil.getUserID(session));
							article.setCreateDate(new Date());
//							ArticleType articleType = articleTypeService.selectByPrimaryKey(36);
							article.setArticleTypeId(17);
							article.setStatus(0);
							article.setClickRate(0);
							article.setCollectNum(0);
							article.setSupportNum(0);
							article.setOpposeNum(0);
							articleService.insert(article);
						}
					}
					
				}
			/*Document doc = Jsoup.connect("http://blog.csdn.net/database/newarticle.html")
					.timeout(5000)
					.get();
			Elements es = doc.select(".blog_list.clearfix>dd>h3>a");
			Elements es2 = doc.select(".blog_list.clearfix>dd>div.blog_list_c");
			for (int i = 0; i < es.size(); i++) {
				Element e = es.get(i);
				String href = e.attr("href");
				String text = e.text();
				Document document= Jsoup.connect(href)
						.timeout(5000)
						.get();
//				String body = "<html><head></head><body>"+document.select("#article_content>div").first()+"</body></html>";
				Element ess = document.select("#article_content>div").first();
				if(ess != null){
					String articleContent = ess.toString();
					if(articleContent != null && !"".equals(articleContent) && !"null".equals(articleContent)){
						Article article = new Article();
						article.setArticleTitle(text);
						article.setArticleBriefIntroduction(es2.get(i).text());
						article.setArticleContent(articleContent);
						article.setUserId(SessionUtil.getUserID(session));
						article.setCreateDate(new Date());
//						ArticleType articleType = articleTypeService.selectByPrimaryKey(36);
						article.setArticleTypeId(36);
						article.setStatus(0);
						articleService.insert(article);
					}
				}
			}*/
			
			json.setSuccess(true);
			json.setMessage("添加成功!");
		} catch (IOException e) {
			e.printStackTrace();
			json.setMessage("添加失败!");
			json.setSuccess(false);
		}
		return json;
	}
	
	/**
	 * 管理员审核文章状态
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("review")
	@ResponseBody
	public JsonObj review(@RequestParam(value="ids[]")Integer[] ids,Integer status,HttpServletRequest request){
		JsonObj json = new JsonObj();
		try {
			for (int i = 0; i < ids.length; i++) {
				Article article = new Article();
				article.setId(ids[i]);
				article.setStatus(status);
				articleService.updateReview(article);
			}
			json.setSuccess(Constant.S);
			json.setMessage(Constant.SUCCESS_MSG);
		} catch (Exception e) {
			//e.printStackTrace();
			json.setSuccess(Constant.F);
			json.setMessage(Constant.FAIL_MSG);
		}
		return json;
	}
}
